package com.booklove.controller.delivery;

import com.booklove.context.BaseContext;
import com.booklove.domain.dto.PageDTO;
import com.booklove.domain.query.AddressQuery;
import com.booklove.domain.vo.AddressVO;
import com.booklove.result.Result;
import com.booklove.service.delivery.AddressService;
import com.booklove.domain.dto.AddressFormDTO;
import com.booklove.domain.po.Address;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;


@Slf4j
@RestController("addressCLL")
@RequestMapping("/address")
@RequiredArgsConstructor// 使用基本注解的注入形式，仅仅注入需要的变量
public class AddressController {

    private final AddressService addressService;

    /**
     * 保存新增
     */
    @PostMapping("/")
    Result<Address> saveAddress(@RequestBody AddressFormDTO addressFormDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressFormDTO, address);
        address.setUserId(BaseContext.getCurrentId().intValue());
        address.setCreatedTime(LocalDateTime.now());
        address.setUpdatedTime(LocalDateTime.now());
        address.setCreatedBy(BaseContext.getCurrentId().intValue());
        address.setUpdatedBy(BaseContext.getCurrentId().intValue());
        addressService.save(address);
        return Result.success(address);
    }


    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/id")
    Result<String> deleteAddress(@RequestParam("id") Long id) {
        addressService.removeById(id);
        return Result.success();
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    AddressVO getAddress(@PathVariable Long id) {
        Address address=addressService.getById(id);
        AddressVO addressVO=new AddressVO();
        BeanUtils.copyProperties(address,addressVO);
        return addressVO;
    }


    /**
     * 编辑数据
     *
     * @param addressFormDTO 实体
     * @return 编辑结果
     */
    @PutMapping("/")
    Result<String> updateAddress(@RequestBody AddressFormDTO addressFormDTO) {
        Address address=new Address();
        BeanUtils.copyProperties(addressFormDTO,address);
        address.setUpdatedTime(LocalDateTime.now());
        address.setUpdatedBy(BaseContext.getCurrentId().intValue());
        addressService.updateById(address);
        return Result.success();
    }


    /**
     * 分页查询
     *
     * @param addressQuery 筛选条件
     * @return 查询结果
     */
    @GetMapping("/page")
    PageDTO<AddressVO> addresssPageQuery(AddressQuery addressQuery) {
        return addressService.queryAddresssPage(addressQuery);
    }

}

